import { Toast } from 'vant'
import { Message } from 'element-ui'
import { getPlatform, isWxBrowser } from '@/utils'
const { DOMAIN, COOKIE_NAME } = window.$globalconfig

export default {
  // 获取全cookie
  getCookie (cname = COOKIE_NAME) {
    let cookieStr = ''
    let name = cname + '='
    let cArr = document.cookie.split(';')
    let cookie = ''
    cArr && cArr.map(item => item.trim().indexOf(name) === 0 && (cookie = item))
    if (cookie) {
      cookieStr = decodeURIComponent(cookie.split(name)[1])
    }
    // cookieStr = access_token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTA0NTcsImlhdCI6MTYyMDg4NjIzNSwidWlwIjoiMjE4LjY2LjQ1LjI1NSIsInNjb3BlIjowfQ.6gqDru51l82Yo3WwfiCpRSP3tjHomGtjEdgbudQWWvE&nickname=%E8%BD%AC%E8%BA%AB%E7%9A%84%E6%9C%9D%E9%98%B3&avatar=https%3A%2F%2Fthirdwx.qlogo.cn%2Fmmopen%2Fvi_32%2FDYAIOgq83erAel8rH1xlPHlsOicBibZJsLs8Tq8lerC1lwAmTQicqvTP7BbCLOWtjTarbQAEtdd7c0iaO0uxPjQXGQ%2F132&id=10457&user_id=10457&openid=oISentyiTl-7XeZkmWzRh140eQ3k
    if (cookieStr) {
      return cookieStr
    } else {
      return ''
    }
  },
  // 获取cookie上的某个值
  getUserCookie (name) {
    let cookieStr = this.getCookie()

    let str = ''
    if (cookieStr) {
      str = this.getURLQuery(cookieStr)[name] || ''
    }
    return str
    // var arr = cookieStr.replace(/\s/g, "").replace(/;/g, "&").split('&')
    // for (var i = 0; i < arr.length; i++) {
    //   var tempArr = arr[i].split('=')

    //   if (tempArr[tempArr.length - 2] == name) {
    //     return decodeURIComponent(decodeURIComponent(tempArr[tempArr.length - 1]))
    //   }
    // }
    // return ''
  },
  // 检测是否登录
  checkLogin (val) {
    // val=1直接弹出登录框，不需要验证
    if (val !== 1) {
      let token = this.getUserCookie('access_token')
      if (token) {
        return true
      }
    }

    if(!isWxBrowser()) {
      getPlatform() ? Message({message: '请先登录', type: 'warning'}) : Toast({message: '请先登录', type: 'fail'})
    }

    setTimeout(() => {
      if(isWxBrowser()) {
        if(!this.getCookie()) {
          this.weixinAuth($VM.$route.params.panoId)
        }
      } else {
        $VM.$vgo.emit('login:show')
      }
    }, 1000)

    return false
  },
  // setCookie (name, value, minute) {
  //   var exp = new Date()
  //   exp.setTime(exp.getTime() + minute * 1000 * 60)
  //   var domain = ''
  //   if(process.env.NODE_ENV != 'development') {
  //     domain = $globalconfig.CookieDoMain
  //   }
  //   document.cookie = name + '=' + value + ';expires=' + exp.toGMTString() + domain
  // },
  setCookie (cname, cvalue = null, opts = {}) {
    // 默认1天
    const { exHours = 24, domain = '', path = '/' } = opts
    let expires = ''
    if (exHours) {
      const date = new Date()
      date.setTime(date.getTime() + (exHours * 60 * 60 * 1000))
      expires = ';expires=' + date.toGMTString()
    }
    const pathHandle = ';path=' + path
    const domainHandle = domain ? ';domain=' + domain : ''
    cvalue = typeof cvalue === 'object' ? JSON.stringify(cvalue) : cvalue
    document.cookie = cname + '=' + cvalue + expires + pathHandle + domainHandle
  },
  /**
   * 设置token
   *
   * @param {String} token
   */
  setToken (token) {
    let h = 2
    if (token) {
      let obj = this.getURLQuery(token)
      if (obj && obj.expires_in) {
        h = Number(obj.expires_in) || 2
      }
    }
    this.setCookie(COOKIE_NAME, token, { exHours: h, domain: process.env.NODE_ENV === 'production' ? DOMAIN : '' })
  },
  // 获取token
  getToken (val = false) {
    let token = this.getUserCookie('access_token')
    if (token) {
      return token
    } else {
      // val=true跳转登录
      if (val) {
        this.checkLogin(1)
      }
      return ''
    }
  },
  delCookie (name = COOKIE_NAME) {
    // 设置已过期，系统会立刻删除cookie
    this.setCookie(name, '', { exHours: -1, domain: process.env.NODE_ENV === 'production' ? DOMAIN : '' })
  },
  // 微信授权登录
  weixinAuth (panoId) {
    // window.location.href = `${$globalconfig.URLS.API}api/wxopen/authorize/get?pano_id=${panoId}`
    window.location.replace(`${window.$globalconfig.URLS.API}oauth/mp/authorize?redirect_uri=${encodeURIComponent(window.location.href)}`)
  },
  getHrefData (url) {
    var arr = url.split('?')
    var data = {}
    if (arr.length >= 2) {
      var dataarr = arr[1].split('&')
      for (var i = 0; i < dataarr.length; i++) {
        var temparr = dataarr[i].split('=')
        data[temparr[0]] = decodeURIComponent(temparr[1])
      }
    }
    return data
  },
  /**
   * 获取url query 查询对象 {a: 1}
   *
   * @param {String} url
   */
  getURLQuery (url = location.href) {
    var obj = {}
    var reg = /([^?&=]+)=([^?&=]+)/g
    let res = reg.exec(url)
    while (res) {
      obj[res[1]] = res[2]
      res = reg.exec(url)
    }
    var rObj = {}
    for (var i in obj) {
      rObj[i] = decodeURIComponent(obj[i])
    }
    return rObj
  },
}
